package edu.del.teamknowledgebase.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

@Slf4j
public class FileUploadUtil {

    private static final String UPLOAD_DIR = "images/avatars/";

    /**
     * 获取 static 目录的绝对路径
     * 兼容 Windows 和 Linux 系统
     */
    private static String getStaticPath() {
        try {
            // 使用 toURI() 解决 Windows 路径问题
            File classPathFile = new File(Objects.requireNonNull(
                    FileUploadUtil.class.getResource("/")
            ).toURI());
            return classPathFile.getAbsolutePath() + File.separator + "static" + File.separator;
        } catch (URISyntaxException e) {
            log.error("获取静态资源路径失败: {}", e.getMessage());
            throw new RuntimeException("无法获取静态资源路径", e);
        }
    }

    /**
     * 上传头像
     * @param file 头像文件
     * @return 头像路径
     */
    public static String uploadAvatar(MultipartFile file) throws IOException {
        // 生成新的文件名并构建上传路径
        String originalFilename = file.getOriginalFilename();
        String extedName = FileUtil.extName(originalFilename);
        String newFileName = IdUtil.simpleUUID() + "." + extedName;

        String staticPath = getStaticPath();
        String uploadPath = staticPath + UPLOAD_DIR;
        File uploadDir = new File(uploadPath);

        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 保存文件到服务器并返回访问路径
        String filePath = uploadPath + newFileName;
        Path path = Paths.get(filePath);
        Files.write(path, file.getBytes());

        return "/" + UPLOAD_DIR + newFileName;
    }

    /**
     * 删除头像
     * @param avatarPath 头像路径
     */
    public static void deleteAvatar(String avatarPath) {
        try {
            if (avatarPath.startsWith("/" + UPLOAD_DIR)) {
                String staticPath = getStaticPath();
                String filePath = staticPath + avatarPath.substring(1);
                File file = new File(filePath);
                if (file.exists()) {
                    file.delete();
                    log.info("删除旧头像: {}", avatarPath);
                }
            }
        } catch (Exception e) {
            log.error("删除头像失败: {}", e.getMessage());
        }
    }
}
